package com.cec.interceptor;

import com.cec.context.BaseContext;
import com.cec.exception.InvalidTokenException;
import com.cec.properties.JwtProperties;
import com.cec.result.ResultCode;
import com.cec.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class JwtTokenAdminInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader == null)
            throw new InvalidTokenException(ResultCode.NOT_LOGIN);
        String token = authorizationHeader.replace("Bearer ", "");

        log.info("token-->{}", token);
        if (token == null)
            throw new InvalidTokenException(ResultCode.INVALID_TOKEN);
        //2、校验令牌
        try {
            Claims claims = JwtUtil.parserToken(jwtProperties.getAdminSecretKey(), token);

            Integer adminId = Integer.valueOf(claims.get("adminId").toString());
            BaseContext.setCurrentId(adminId);

            return true;
        } catch (Exception ex) {
            //log.info("拦截器捕获异常");
            //4、不通过，响应401状态码
            //response.setStatus(401);
            //log.info("token过期");
            //return false;
            throw new InvalidTokenException(ResultCode.TOKEN_EXPIRED);
            //需求分析（产品模型、需求规格说明书）、设计（产品文档、UI界面设计、概要设计、详细设计、数据库设计、用例图）、编码（项目代码、单元测试）、测试（测试用例、测试报告）、上线运维（软件环境、配置）
        }

    }
}
